package com.huayun.plugin.pointcloud.util;

import com.huayun.plugin.pointcloud.domain.Point;
import java.io.*;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
 * 点云PCD格式文件解析
 * */
public class PCDFileParser {
    private final Logger log = LoggerFactory.getLogger(PCDFileParser.class);

    private List<Point> cloudPoints = new ArrayList<>();

    public PCDFileParser(File file) throws FileNotFoundException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    }

    public PCDFileParser(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        cloudPoints = parserPointCloudData(reader);
    }

    /*
     * 读取点坐标
     * */
    private List<Point> parserPointCloudData(BufferedReader reader) throws IOException {
        List<Point> pointList = new ArrayList<>();
        String line;
        Boolean startPoint = false; //是否开始存储点坐标
        while ((line = reader.readLine()) != null) {
            if (startPoint) {
                String[] lineValues = line.split(" ");
                if (Arrays.stream(lineValues).count() == 3) {
                    double pointX = Double.parseDouble(lineValues[0]);
                    double pointY = Double.parseDouble(lineValues[1]);
                    double pointZ = Double.parseDouble(lineValues[2]);
                    Point point = new Point(pointX, pointY, pointZ);
                    pointList.add(point);
                }
            }
            if (line.startsWith("DATA")) {
                startPoint = true;
            }
        }
        return pointList;
    }

    public  List<Point> GetPoints() { return cloudPoints; }
}